package org.exercise.record.controller;


import org.exercise.record.domain.User;
import org.exercise.record.dto.request.UserRegisterDTO;
import org.exercise.record.service.UserService;
import org.exercise.record.service.UserServiceImpl;
import org.exercise.record.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.exercise.record.utils.ResponseUtils.makeErrorResponse;
import static org.exercise.record.utils.ResponseUtils.makeSuccessResponse;

@RestController
@RequestMapping(value="/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/test")
    public String test() {
        return "这是我的第一个Springboot接口";
    }

    /**
     * 获取列表
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public List<User> listAllUser() {
        return userService.listUser();
    }


    @GetMapping("/find")
    @ResponseBody
    public User getUserByName(@RequestParam("Username") String username) {
        return userService.getByUsername(username);
    }

    @PostMapping("/login")
    public Result loginController(@RequestParam String username, @RequestParam String password) {
        User user = userService.loginService(username, password);
        if (user != null) {
            return makeSuccessResponse("登陆成功", user);
        } else {
            return makeErrorResponse("账号或密码输入错误.");
        }
    }

    // 实现注册功能
    @PostMapping("/register")
    public Result registerController(@RequestBody UserRegisterDTO userRegisterDTO) {
        User newUser = new User();
        newUser.setUsername(userRegisterDTO.getUsername());
        newUser.setPassword(userRegisterDTO.getPassword());
        if (userRegisterDTO.getEmail() == null) {
            newUser.setEmail("该用户未填写邮箱.");
        } else {
            newUser.setEmail(userRegisterDTO.getEmail());
        }
        if (userRegisterDTO.getAge() == null) {
            newUser.setAge(-1);
        } else {
            newUser.setAge(userRegisterDTO.getAge());
        }

        int registerResult = userService.registerService(newUser);
        System.out.println(registerResult);
        if (registerResult > 0) {
            return makeSuccessResponse("注册成功", registerResult);
        } else {
            // 注册失败
            return makeErrorResponse("注册失败，用户名已存在");
        }
    }

}
